<template>
  <CloudDialog
    v-model:visible="visible"
    :loading="loading"
    :title="isEdit ? '编辑用户' : '添加用户'"
    :width="480"
    :before-close="handleClose"
    :before-ok="handleSubmit">
    <a-spin :loading="loading" class="w-full">
      <a-form ref="formRef" layout="vertical" :model="formState" :rules="rules">
        <a-form-item label="用户账号" hide-asterisk field="username">
          <a-input v-model.trim="formState.username" placeholder="请输入账号" />
        </a-form-item>
        <a-form-item label="邮箱" hide-asterisk field="email">
          <a-input v-model.trim="formState.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item v-if="!isEdit" label="密码" hide-asterisk field="password">
          <a-input
            v-model.trim="formState.password"
            :max-length="20"
            placeholder="请输入密码"
            class="cloud-pwd-icon"
            @input="
              (value: string) => (formState.password = value.replace(/\s/g, ''))
            ">
            <template #suffix>
              <span
                class="text-#11429D cursor-pointer"
                @click="handleRandomKey">
                随机
              </span>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="备注" hide-asterisk field="remark">
          <a-input
            v-model.trim="formState.remark"
            placeholder="请输入备注"
            :max-length="20"
            show-word-limit />
        </a-form-item>
        <a-form-item label="启用状态" hide-asterisk field="status">
          <a-radio-group v-model="formState.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="2">停用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-spin>
  </CloudDialog>
</template>
<script lang="ts" setup>
import {
  addAdminApiUserCreateApi,
  getAdminApiUserDetailApi,
  updateAdminApiUserUpdateApi
} from '@/apis/modules/user'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
import { cloneDeep } from 'lodash-es'
interface Props {
  record?: any
}
const props = defineProps<Props>()
const visible = defineModel<boolean>('visible', { required: true })
interface IEmits {
  (e: 'refresh'): void
}
const emits = defineEmits<IEmits>()
const formRef = ref<FormInstance>()
const formState = ref({
  username: '',
  email: '',
  password: '',
  status: 1,
  remark: ''
})
const isEdit = computed(() => !!props.record?.id)
const rules = computed<Record<string, FieldRule[]>>(() => {
  const res: Record<string, FieldRule[]> = {
    username: [
      { required: true, message: '请输入账号' },
      {
        validator: validateAccount
      }
    ],
    email: [
      { required: false, type: 'email', message: '邮箱地址格式不正确' },
      {
        maxLength: 320,
        message: '邮箱地址长度不能超过320个字符'
      }
    ],
    password: [
      {
        required: true,
        validator: validatePassword
      }
    ]
  }
  return res
})
function handleRandomKey() {
  const randomString = generateRandomThreeTypesString(8, 20)
  formState.value.password = randomString
  formRef.value?.validateField(['password'])
}
const handleClose = () => {
  visible.value = false
}
const handleSubmit = async () => {
  const error = await formRef.value?.validate()
  if (error) return false
  loading.value = true
  const apiPath = isEdit.value
    ? updateAdminApiUserUpdateApi
    : addAdminApiUserCreateApi
  const params = {
    ...formState.value,
    id: isEdit.value ? props.record?.id : undefined
  }
  await apiPath(params as any)
    .then(() => {
      ToastUtils.success('操作成功')
      visible.value = false
      emits('refresh')
    })
    .finally(() => (loading.value = false))
}
const { loading, request: getUserDetail } = useRequest(
  getAdminApiUserDetailApi,
  {
    success(res) {
      Object.assign(formState.value, cloneDeep(res))
      // coverObjectValue(formData, res!)
    }
  }
)
watch(
  () => visible.value,
  async (v) => {
    await nextTick()
    if (v) {
      if (isEdit.value) getUserDetail({ id: props.record?.id })
    } else {
      formRef.value?.resetFields()
    }
  }
)
</script>

<style lang="less" scoped></style>
